<?php
namespace App\Http\Controllers\Api;

use App\Http\Resources\Api\Tournaments as TournamentCollection;
use App\Models\Tournament;
use App\Models\TournamentUser;
use Illuminate\Http\Request;

class TournamentsController extends Controller
{
    public function index()
    {
        $now = time();
        $result = Tournament::where('start_time', '<', $now)
            ->where('end_time', '>', $now)
            ->get();

        return new TournamentCollection($result);
    }

    // 进入联赛
    public function play(Request $request, $id)
    {
        $tournament = Tournament::findOrFail($id);
        $userId = app('auth')->id();

        // 验证联赛是否有效
        $now = time();
        $isUnlock = $tournament->start_time < $now && $tournament->end_time > $now;

        if (!$isUnlock) {
            return invalidation('this tournament is locked');
        }

        // 生成用户巡回赛数据
        TournamentUser::updateOrCreate([
            'user_id' => $userId,
            'tournament_id' => $tournament->id,
        ],
            [
                'status' => TournamentUser::STATUS_NORMAL,
            ]);

        // 返回数据
        return [
            //自动匹配后客户端进入该链接（游戏已开始，等待进入）
            'ws_url' => 'ws://' . get_server_addr() . '/tournament/' . $tournament->id . '?uid=' . $userId,
        ];
    }

    // // 获取正在进行的联赛
    // public function check()
    // {
    //     $userId = app('auth')->id();

    //     $tournament = Tournament::join('tournament_users', 'tournament_users.tournament_id', '=', 'tournaments.id')
    //         ->where('tournament_users.user_id', $userId)
    //         ->whereRaw('tournament_users.status <> 0')
    //         ->first();
    //     if ($tournament) {
    //         return $tournament->toArray() + [
    //             'ws_url' => 'ws://' . get_server_addr() . '/integral/' . $tournament->id . '?uid=' . $userId,
    //         ];
    //     }
    //     return [];

    // }
}
